﻿using System;
using System.Threading;
using System.Threading.Tasks;
using K9Nano.Caching;
using K9Nano.Dependency;
using K9Nano.Domain;
using K9Nano.Share;

namespace K9Nano.Caching
{
    public class DefaultSharedOrganizationCache : ISharedOrganizationCache, IScopedDependency
    {
        protected readonly ITypedCache<SharedOrganizationCacheItem> Cache;
        protected readonly IReadOnlyRepository ReadOnlyRepository;

        public DefaultSharedOrganizationCache(IReadOnlyRepository readOnlyRepository, ITypedCache<SharedOrganizationCacheItem> cache)
        {
            ReadOnlyRepository = readOnlyRepository;
            Cache = cache;
        }
        public SharedOrganizationCacheItem Get(Guid id)
        {
            return Cache.GetOrAdd(id.ToString(), _ => GetOrganization(id));
        }

        protected virtual SharedOrganizationCacheItem GetOrganization(Guid id)
        {
            var item = ReadOnlyRepository.QueryFirstOrDefault<SharedOrganizationCacheItem>(
                $"select Id, Code, DisplayName, ParentId, Type from {K9SharedConstants.SharedSchemePlaceholder}.app_organization_unit where Id=@id",
                new { id = id.ToString() });
            return item;
        }
    }
}
